package com.qf.xiaomi.service.impl;

import com.qf.xiaomi.dao.OrderDao;
import com.qf.xiaomi.dao.impl.OrderDaoImpl;
import com.qf.xiaomi.pojo.CartUnion;
import com.qf.xiaomi.pojo.OrderDetail;
import com.qf.xiaomi.pojo.OrderList;
import com.qf.xiaomi.service.OrderService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Created by 马英超 on 2022/8/20 17:20
 * @author： 马英超
 * @version：v1.0
 * @description:
 */
public class OrderServiceImpl implements OrderService {
    @Override
    public Map createOrder(int userId, int addressId, List<CartUnion> cart) {
        System.out.println(cart);
        //计算订单总价
        int sumPrice=0;
        for (int i = 0; i < cart.size(); i++) {
            //
            sumPrice +=   cart.get(i).getPrice()*cart.get(i).getNum();
        }
        //设置订单号生成规则
        final String orderCode = UUID.randomUUID().toString().replace("-", "");
       //调用Dao进行数据处理
        OrderDao orderDao=new OrderDaoImpl();
        final int insertResult=  orderDao.insertOrder(userId,orderCode,sumPrice,addressId);
        //向订单中间表插入数据

        int orderDetail=0;
        for (int i = 0; i < cart.size(); i++) {
            orderDetail = orderDao.addOrderDetail(orderCode, cart.get(i).getPid(), cart.get(i).getNum(), cart.get(i).getPrice());
            orderDetail +=orderDetail ;
        }
        //加入购物车够需要清空购物车
        if(insertResult>0){
            orderDao.clearCart(userId);//如果订单创建成功则清空购物车

            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("id",orderCode);
            hashMap.put("money",sumPrice);
            return hashMap;
        }
        return null;
    }

    @Override
    public List<OrderList> queryOrderByUserId(int userId)  {
        //调用OrderDao
        OrderDaoImpl orderDao=new OrderDaoImpl();

        return  orderDao.queryOrderInfo(userId);
    }

    @Override
    public OrderDetail queryOrderDetail(String oid, int userId) {

        //调用Dao
        OrderDao orderDao=new OrderDaoImpl();
        final OrderDetail orderDetail = orderDao.queryOrderDetailInfo(oid, userId);
        if (orderDetail!=null)
            return orderDetail;
        return null;
    }
}
